<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="renderer" content="webkit">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="robots" content="all">
  <meta name="format-detection" content="telephone=no" />
  <title>如何判断一个元素是否在可是区域内</title>
  <style>
    div {
      height: 4000px;
    }
    h1 {
      height: 1800px;
    }
    p {
      height: 200px;
      border: 1px solid #000;
      line-height: 200px;
      text-align: center;
    }
  </style>
</head>
<body>
  <div>
    <h1>1</h1>
    <p id="main">我是该元素</p>
    <h1>2</h1>
  </div>
  <script>
    const mainOffsetTop = document.getElementById('main').offsetTop
    const mainHeight = document.getElementById('main').clientHeight;
    const winHeight = window.innerHeight;
    window.addEventListener('scroll', () => {
      const winScrollTop = window.scrollY
      if (
        winScrollTop > mainOffsetTop + mainHeight ||
        winScrollTop <　mainOffsetTop - winHeight
      ) {
        console.log("不在可是区域内")
      }
      else {
        console.log("在可是区域内")
      }
    })
  </script>
</body>
</html>